package cn.org.timespace.ons.util;

import java.util.Date;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.ons.util.ResourceContext;
import cn.org.timespace.ons.util.datatime.DateTimeUtils;

/**
 * <p>
 * 主键生成器
 * </p>
 * 
 */

public class IdentityGenerator {
	
	private static final Log log = LogFactory.getLog(IdentityGenerator.class);
	
	private static IdentityGenerator identityGenerator;
	
	private static final String DEFAULT_PK_VALUE = "9999999999999999999999";
	private static final String PK_FILL_CHARACTER = "0";
	private static final String ORG_CODE = "org.code";
	private static String orgCode = "00";
	
	private static Integer increaseValue = 1;
	
	private IdentityGenerator(){}
	
	public static IdentityGenerator getInstance(){
		
		if(identityGenerator == null){
			if(log.isDebugEnabled()) log.debug("正在初始化主键生成器。");
			identityGenerator = new IdentityGenerator();
		}
		
		if(orgCode.equals("00")){
			orgCode = ResourceContext.getInstance().getParamValue(ORG_CODE);
			if(log.isInfoEnabled()) log.info("机构编码是："+orgCode);
		}
		
		return identityGenerator;
	}
	
	public synchronized String getId(){
		String res = DEFAULT_PK_VALUE;
		
		String curDateTime = DateTimeUtils.formatDate(new Date(), DateTimeUtils.PATTERN_DATETIME_COMPACT);
		
		if(increaseValue >= Integer.MAX_VALUE){
			increaseValue = 1;
		}
		
		String fullC = fillCharacter(String.valueOf(increaseValue), PK_FILL_CHARACTER, 10);
		res = orgCode + curDateTime + fullC;
		increaseValue++;
		
		if(log.isInfoEnabled()) log.info("当前生成的主键是："+res);
		
		return res;
	}
	
	/**
	 * 填充字符
	 * @param oriC  原始字符
	 * @param fullC 填充字符
	 * @param size  总长度
	 * @return
	 */
	private String fillCharacter(String oriC,String fillC,int size){
		String res = "";
		if(oriC != null){
			int oriCLen = oriC.length();
			for(int i = size - oriCLen;i>0;i--){
				res += fillC;
			}
		}
		res += oriC;
		return res;
	}
	
	
	public static void main(String[] args) {
//		for(int i=0;i<100;i++){
//			IdentityGenerator.getInstance().getId();
//		}
		
	}
	
}
